<?php namespace App\Http\Requests;

use App\Models\Member;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Hashing\BcryptHasher;
use Validator;

class MemberLoginRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
        if($this->ajax()) {
            return true;
        } else {
            return false;
        }
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			'name' => 'required',
            'password' => 'required',
		];
	}

    public function validator()
    {
        $nickname = [
            'name' => '用户名',
            'password' => '密码'
        ];

        $validator = Validator::make($this->input(), $this->rules());
        $validator->setAttributeNames($nickname);

        $validator->after(function($validator) {
            $data = $this->only('name', 'password');
            $member = null;

            try {
                $member = Member::where('name', '=', $data['name'])->firstOrFail();
            } catch(ModelNotFoundException $e) {
                $validator->errors()->add('name', '不存在的用户名');
            }

            if ($member != null) {
                if (!(new BcryptHasher())->check($data['password'], $member->password)) {
                    $validator->errors()->add('password', '密码错误');
                }
            }
        });

        return $validator;
    }
}
